package com.sit.controller;

import com.sit.pojo.*;
import com.sit.utils.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.sit.service.*;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/reader")
public class ReadersController {
    @Autowired
    private ReadersService readersService;
    @Autowired
    private adminService adminService;
    @Autowired
    private EmailUtil emailUtil;

    @RequestMapping("/loginHtml")
    public String loginHtml(){
        return "login";
    }

    @RequestMapping("/registerHtml")
    public String adminMenuHtml(){
        return "register";
    }

    @RequestMapping("forgetPassHtml")
    public String forgetPassHtml(){
        return "forgetPass";
    }

    @RequestMapping("readerIndex")
    public String readerIndex(Model model,HttpSession session){
        Readers readerInfo = readersService.findReaderById((String) session.getAttribute("readId"));
        model.addAttribute("readerInfo", readerInfo);
        return "Reader/readerIndex";
    }

    @RequestMapping("updateReaderPassHtml")
    public String updateReaderPassHtml(){
        return "Reader/updateReaderPass";
    }

    @RequestMapping("readerCardInfoHtml")
    public String readerCardInfoHtml(Model model,HttpSession session){
        js_card jsInfo = readersService.findReaderCard((String) session.getAttribute("readId"));
        model.addAttribute("jsInfo", jsInfo);
        return "Reader/readerCardInfo";
    }

    @RequestMapping("addReaderCardHtml")
    public String addReaderCardHtml(){
        return "Reader/addReaderCard";
    }

    @RequestMapping("/bookListHtml")
    public String bookListHtml(Model model){
        List<books> booksList = adminService.findAllBook();
        List<books_type> booksTypeList = adminService.findAllBookType();
        model.addAttribute("booksList",booksList);
        model.addAttribute("booksTypeList",booksTypeList);
        return "Reader/bookList";
    }

    @RequestMapping("borrowInfoHtml")
    public String borrowInfoHtml(Model model,HttpSession session){
        List<borrow> borrowList = readersService.getBorrow((String) session.getAttribute("readId"));
        model.addAttribute("borrowList",borrowList);
        return "Reader/borrowInfo";
    }

    @RequestMapping("hisborrowInfoHtml")
    public String hisborrowInfoHtml(Model model,HttpSession session){
        List<hisborrow> hisborrowList = readersService.getHisBorrow((String) session.getAttribute("readId"));
        model.addAttribute("hisborrowList",hisborrowList);
        return "Reader/hisborrowInfo";
    }

    @RequestMapping("punishInfoHtml")
    public String punishInfoHtml(Model model,HttpSession session){
        List<punish> punishList = readersService.getPunish((String) session.getAttribute("readId"));
        model.addAttribute("punishList",punishList);
        return "Reader/punishInfo";
    }

    @RequestMapping("BookTopFiveHtml")
    public String BookTopFiveHtml(Model model){
        List<books> booksList = readersService.BookTopFive();
        model.addAttribute("booksList",booksList);
        return "Reader/BookTopFive";
    }

    @RequestMapping("ReaderTopFiveHtml")
    public String ReaderTopFiveHtml(Model model){
        List<Readers> readersList = readersService.ReaderTopFive();
        model.addAttribute("readersList",readersList);
        return "Reader/ReaderTopFive";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestParam("readId") String readId, @RequestParam("password") String password,@RequestParam("captcha") String captcha,HttpSession session,HttpServletRequest request) throws Exception {
        Readers result = null;
        String Token = CaptchaController.verifyCaptcha(request, captcha);
        result = readersService.login(readId);
        if(Token.equals("success")){
            if(result == null)
                return "1";
            if (password.equals(result.getReadPass())) {
                session.setAttribute("readId", readId);
                return "2";
            }else{
                return "3";
            }
        }
        else return "4";
    }

    @RequestMapping("/goOut")
    public String goOut(HttpSession session){
        session.removeAttribute("readId");
        return "redirect:/reader/loginHtml";
    }

    @RequestMapping("/getReadId")
    @ResponseBody
    public String getReadId(HttpSession session){
        return (String) session.getAttribute("readId");
    }

    @RequestMapping("/addReader")
    @ResponseBody
    public String addReader(Readers readers,@RequestParam("captcha") String captcha,HttpServletRequest request) throws Exception {
        int result = 0;
        String res = "false";
        String Token = CaptchaController.verifyCaptcha(request, captcha);
        List<Readers> readersList = adminService.findAllReader();
        if(Token.equals("success")){
            for (Readers value : readersList) {
                if (value.getReadId().equals(readers.getReadId())) {
                    res = "exist";
                    return res;
                }
            }
            result = readersService.addReader(readers);
            if(result!= 0)
                res = "success";
            return res;
        }
        else{
            return "failure";
        }
    }

    @RequestMapping("/sendEmail")
    @ResponseBody
    public boolean sendEmail(@RequestParam("readMail")String readMail,HttpSession session) throws Exception {
        String Token = CaptchaUtil.generateCaptcha(4);
        String subject = "重置密码";
        String content = "你的验证码为：" + Token + "，请在30分钟内使用，如非本人操作，请忽略此邮件";
        boolean res = false;
        String AES_Token = CaptchaUtil.encrypt(Token);
        session.setAttribute("MailCaptcha", AES_Token);
        res = emailUtil.sendGeneralEmail(subject, content, readMail);
        return res;
    }

    @RequestMapping("/forgetPass")
    @ResponseBody
    public String forgetPass(Readers reader,@RequestParam("captcha") String captcha,@RequestParam("newPass")String newPass,@RequestParam("againNewPass")String againNewPass,HttpSession session) throws Exception {
        String AES_Token = (String) session.getAttribute("MailCaptcha");
        String Token = CaptchaUtil.decrypt(AES_Token);
        Readers readerInfo = readersService.findReaderById(reader.getReadId());
        String res = "false";
        if(readerInfo != null){
           if(readerInfo.getReadMail().equals(reader.getReadMail())){
               if(captcha.equalsIgnoreCase(Token)){
                   if(newPass.equals(againNewPass)){
                       reader.setReadPass(newPass);
                       readersService.updateReaderPass(reader);
                       res = "success";
                   }else res = "passError";
               }else res = "captchaError";
           }else res = "mailError";
        }else res = "notExist";
        return res;
    }

    @RequestMapping("updateReader")
    @ResponseBody
    public String updateReader(Readers readers){
        int result = 0;
        String res = "false";
        result = readersService.updateReader(readers);
        if(result!= 0) {
            res = "success";
            return res;
        }
        return res;
    }

    @RequestMapping("addReaderCard")
    @ResponseBody
    public String addReaderCard(js_card card){
        String res = "false";
        int result = 0;
        js_card cardInfo = readersService.findReaderCard(card.getReadId());
        if(cardInfo == null){
            result = readersService.addReaderCard(card);
            if(result!= 0) {
                res = "success";
                return res;
            }
        }else{
            res = "exist";
            return res;
        }
        return res;
    }

    @RequestMapping("deleteReader")
    @ResponseBody
    public String deleteReader(@RequestParam("readId")String readId){
        int result = 0;
        int result1 = 0;
        js_card card = null;
        card = readersService.findReaderCard(readId);
        String res = "false";
        if(card == null){
            result = adminService.deleteReader(readId);
            if(result!= 0) {
                res = "success";
                return res;
            }
        }else if(card.getJsId() != null){
            result1 = adminService.deleteReaderCard(card.getReadId());
            result = adminService.deleteReader(readId);
            if(result!= 0 && result1!=0) {
                res = "success";
                return res;
            }
        }
        return res;
    }

    @RequestMapping("deleteReaderCard")
    @ResponseBody
    public String deleteReaderCard(@RequestParam("readId")String readId){
        String res = "false";
        int result = 0;
        js_card cardInfo = readersService.findReaderCard(readId);
        if(cardInfo != null){
            result = readersService.deleteReaderCard(readId);
            if(result != 0){
                res = "success";
                return res;
            }
        }else{
            res = "notExist";
            return res;
        }
        return res;
    }

    @RequestMapping("findBookByName")
    @ResponseBody
    public List<books> findBookByName(String name){
        List<books> books = null;
        books = readersService.findBookByName(name);
        return books;
    }

    @RequestMapping("findBookByInput")
    @ResponseBody
    public List<books> findBookByInput(books book){
        return readersService.findBookByInput(book);
    }

    @RequestMapping("findBookTypeByInput")
    @ResponseBody
    public List<books_type> findBookTypeByInput(books_type bookType){
        return readersService.findBookTypeByInput(bookType);
    }

    @RequestMapping("borrowBook")
    @ResponseBody
    public String borrowBook(@RequestParam("readId")String readId,@RequestParam("bookId")String bookId){
        int result = 0;
        Readers reader = null;
        books book = null;
        js_card card = null;
        List<punish> punish = null;
        reader = readersService.findReaderById(readId);
        book = adminService.findBookById(bookId);
        card = readersService.findReaderCard(readId);
        punish = readersService.getPunish(readId);
        if(book.getBookSum() > 0 && reader.getRbSum() < 6 && punish.isEmpty() && card != null){
            result = readersService.borrowBook(readId,bookId);
            if (result != 0) {
                return "1";
            }
        }else if (card == null){
            return "2";
        }else if (!punish.isEmpty()){
            return "3";
        }else if (reader.getRbSum() >= 6){
            return "4";
        }else if (book.getBookSum() <= 0){
            return "5";
        }
        return "0";
    }

    @RequestMapping("/renewBook")
    @ResponseBody
    public String renewBook(@RequestParam("readId")String readId,@RequestParam("bookId")String bookId,@RequestParam("check")String check,@RequestParam("count")long count) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long day = 86400000L;
        long week = 7 * day;
        long month = 30 * day;
        borrow borrow = readersService.getBorrowInfo(readId,bookId);
        String time = "";
        String res = "false";
        int result = 0;
        if (borrow != null){
            switch (check) {
                case "day" -> time = sdf.format(borrow.getDuedate().getTime() + day * count);
                case "week" -> time = sdf.format(borrow.getDuedate().getTime() + week * count);
                case "month" -> time = sdf.format(borrow.getDuedate().getTime() + month * count);
            }
            Date due_time = sdf.parse(time);
            java.sql.Date sqlDate = new java.sql.Date(due_time.getTime());
            result = readersService.renewBook(readId,bookId,sqlDate);
            if(result!= 0){
                res = "success";
                return res;
            }else return res;
        }
        res = "notExist";
        return res;
    }

    @RequestMapping("returnBook")
    @ResponseBody
    public String returnBook(@RequestParam("readId")String readId,@RequestParam("bookId")String bookId){
        int result = 0;
        Date date = new Date();
        borrow borrow = null;
        borrow = readersService.getBorrowInfo(readId,bookId);
        if(borrow == null){
            return "1";
        }else{
            if(date.compareTo(borrow.getDuedate()) > 0){
                result = readersService.returnBook(readId,bookId);
                if(result != 0){
                    return "2";
                }
            }else{
                result = readersService.returnBook(readId,bookId);
                if(result!= 0){
                    return "3";
                }
            }
        }
        return "0";
    }

    @RequestMapping("/updatepass")
    @ResponseBody
    public String updatepass(@RequestParam("oldPass")String oldPass,@RequestParam("newPass")String newPass,@RequestParam("againNewPass")String againNewPass,@RequestParam("readId")String readId){
        int result = 0;
        Readers reader = readersService.findReaderById(readId);
        if(reader != null){
            if(reader.getReadPass().equals(oldPass)){
                if(newPass.equals(againNewPass)){
                    reader.setReadPass(newPass);
                    result = readersService.updateReaderPass(reader);
                    if (result != 0){
                        return "1";
                    }else return "0";
                }else return "2";
            }else return "3";
        }else return "0";
    }

    @RequestMapping("/checkId")
    @ResponseBody
    public String checkId(@RequestParam("readId")String readId){
        String result = "notExist";
        List<Readers> readers = adminService.findAllReader();
        for (Readers reader : readers) {
            if(reader.getReadId().equals(readId)){
                result = "exist";
                break;
            }
        }
        return result;
    }

    @RequestMapping("getReaderInfo")
    @ResponseBody
    public Readers getReaderInfo(HttpSession session){
        return readersService.findReaderById((String)session.getAttribute("readId"));
    }

    @RequestMapping("getReaderCardInfo")
    @ResponseBody
    public js_card getReaderCardInfo(HttpSession session){
        return readersService.findReaderCard((String)session.getAttribute("readId"));
    }

    @RequestMapping("getBooksInfo")
    @ResponseBody
    public List<books> getBooksInfo(){
        return adminService.findAllBook();
    }

    @RequestMapping("getBorrowInfo")
    @ResponseBody
    public List<borrow> getBorrowInfo(HttpSession session){
        return readersService.getBorrow((String)session.getAttribute("readId"));
    }

    @RequestMapping("getHisBorrowInfo")
    @ResponseBody
    public List<hisborrow> getBorrowInfoByReadId(HttpSession session){
        return readersService.getHisBorrow((String)session.getAttribute("readId"));
    }

    @RequestMapping("getPunishInfo")
    @ResponseBody
    public List<punish> getPunishInfo(HttpSession session){
        return readersService.getPunish((String)session.getAttribute("readId"));
    }
}
